package cn.zclong.article.web.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.servlet.BaseServlet;
import cn.zclong.article.domain.Article;
import cn.zclong.article.domain.PageBean;
import cn.zclong.article.service.ArticleService;
import cn.zclong.reply.web.servlet.ReplyServlet;

/**
 * Servlet implementation class TitleServlet
 */
public class ArticleServlet1 extends BaseServlet {
	private ArticleService articleService = new ArticleService();
	
	private ReplyServlet replyServlet = new ReplyServlet();
	
	/*
	 * 根据id查找帖子，显示帖子的内容
	 */
	@SuppressWarnings("deprecation")
	public String findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		/*
		 * 评论帖子
		 */
//		replyServlet.addReply(request, response);
		/*
		 * 得到登录者id
		 */
		String userid = request.getParameter("userid");
		request.setAttribute("userid", userid);
		
		/*
		 * 得到ReplyServlet对象，调用findAll方法
		 * 查询该帖子的所有评论
		 */
		replyServlet.findAll(request, response);
		
		//得到帖子的id
		String id = request.getParameter("id");
		String readnum = request.getParameter("readnum");
		System.out.println("lllllllllllll");
		//得到Article对象
		Article form = articleService.findAllById(id, readnum);
		System.out.println("kkkkkkkkkkkkkk");
		//得到时间
		long time = form.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time1 =  sdf.format(new Date(time));
		request.setAttribute("time1", time1);
		
		request.setAttribute("form", form);
		
		return "f:/jsps/article/article.jsp";
	}
	
	
	
	/*
	 * 显示热门帖子和所有帖子在主页上
	 */
	public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//得到前五条阅读量最多的数据
		request.setAttribute("articleList", articleService.findAllByReadnum());
		
		/*
		 * 得到用户的id
		 */
		String userid = request.getParameter("userid");
		/*
		 * 分页查询所有数据
		 * 1，获取页面传递的pc当前页码
		 * 2，给定ps的值，每页记录数
		 * 3，使用pc和ps调用的service方法，得到PageBean,保存到request域
		 * 4，转发到in.jsp
		 */
		int pc = getPc(request);//得到pc
		int ps = 5;//给定ps的值，每页五行记录
		PageBean<Article> pb = articleService.findAll(pc, ps);//传递pc和ps给service方法，得到PageBean
		request.setAttribute("pb", pb);//保存到request域
		request.setAttribute("userid", userid);
		return "f:/in.jsp";
	}
	
	/*
	 * 获取pc当前页码
	 */
	public int getPc(HttpServletRequest request) {
		String value = request.getParameter("pc");
		if(value == null || value.trim().isEmpty()) {
			return 1;//pc位null，表示只有一页
		}
		return Integer.parseInt(value);//把pc转换成int类型
	}
}
